package org.xxpay.pay.channel.yipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.channel.PayConfig;
import org.xxpay.pay.channel.shengfutong.SftpayConfig;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
public class YipayPaymentService extends BasePayment {
    private final static String logPrefix = "【易支付】";

    @Override
    public String getChannelName() {
        return YipayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case YipayConfig.CHANMEL_NAME_YIPAY_ALIPAY_WAP:
                retObj = doOrderReq(payOrder,"904");
                break;
            case YipayConfig.CHANNEL_NAME_YIPAY_ALIPAY_QR:
                retObj = doOrderReq(payOrder,"903");
                break;
            case YipayConfig.CHANNEL_NAME_YIPAY_WX_H5:
                retObj = doOrderReq(payOrder,"917");
                break;
            case YipayConfig.CHANNEL_NAME_YIPAY_WX_QR:
                retObj = doOrderReq(payOrder,"902");
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        YipayConfig config = new YipayConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询易付通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String,Object> parameters = Maps.newHashMap();
        parameters.put("pay_memberid", config.getAppId());
        parameters.put("pay_orderid", payOrderId);
        parameters.put("pay_md5sign", getSign(parameters, config.getPrivateKey()));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(getReqUrl(YipayConfig.DOMAIN, YipayConfig.QUERY_STRING_QUERY), parameters, JSONObject.class);
        _log.info("{}易付查单同步请求响应参数：{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("returncode"), YipayConfig.RETURN_VALUE_SUCCESS)) {
            // 易付订单支付状态：1-为已⽀支付，其它未⽀支付
            String payStatus = origin.getString("trade_state");
            // 已支付
            if(StringUtils.equals(YipayConfig.ORDER_STATUS_SUCCESS, payStatus)) {
                retObj.put("status", 2);
            } else {
                // 支付中
                retObj.put("status", 1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("orderid"));
            retObj.put("channelObj", origin.toJSONString());
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }

    //下单请求实现
    private JSONObject doOrderReq(PayOrder payOrder,String payType){
        YipayConfig config = new YipayConfig(getPayParam(payOrder));
        Map<String,Object> parameters = Maps.newHashMap();
        setParams(parameters,payOrder,config,payType);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(parameters));
        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);

        JSONObject retObj = new JSONObject();
        String payForm = HtmlUtils.form(getReqUrl(YipayConfig.DOMAIN, YipayConfig.QUERY_STRING_PAY), HtmlUtils.POST, parameters);

        return buildPayResultOfForm(retObj, payOrder, payForm);
    }

    /**
     * 设置支付请求参数
     * @param map
     * @param payOrder
     * @param config
     */
    private void setParams(Map<String,Object> map, PayOrder payOrder, YipayConfig config, String payType){
        map.put("pay_memberid",config.getAppId());
        map.put("pay_orderid", payOrder.getPayOrderId());
        map.put("pay_applydate", DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
        map.put("pay_bankcode", payType);//银行编码
        map.put("pay_notifyurl", config.getRequestUrl());
        map.put("pay_amount", payOrder.getAmount());
        map.put("pay_md5sign", getSign(map, config.getPrivateKey()));
        map.put("pay_productname", payOrder.getPayOrderId());
    }

    /**
     * 签名
     * @param parameters
     * @param key
     * @return
     */
    private String getSign(Map<String,Object> parameters,String key){
        String signTxt = SignUtils.parameterText(parameters);
        _log.info("{}易支付签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8);
        return sign.toUpperCase();
    }

}
